#include "data_manager.h"
#include "common.h"

#include "FreeRTOS.h"
#include "task.h"

#define MACHINE_ROM_ADDR 0

static int MachineSaveData(PT_ROMDataStruct ptROMData);
static int MachineGetData(PT_ROMDataStruct ptROMData);
static void MachineFreeMalloc(void);

static T_SaveOpr g_tMachineDataOpr = {
	.name     = "machinedata",
	.SaveData = MachineSaveData,
	.GetData  = MachineGetData,
	.FreeMalloc = MachineFreeMalloc,
};

static PT_SenseDataStruct g_ptSenseMalloc;

static int MachineSaveData(PT_ROMDataStruct ptROMData)
{
	uint8_t ucBuffer[64];
	uint8_t i = 0,uclen;
	uint16_t CrcData;
	PT_SenseDataStruct ptTemp;
	
	ucBuffer[0] = ptROMData->Num;
	ucBuffer[1] = ptROMData->SendTime >> 8;
	ucBuffer[2] = ptROMData->SendTime;
	
	ptTemp = ptROMData->SenseDataHead;
	while(ptTemp)
	{
		ucBuffer[3 + i * 6] = ptTemp->Addr[0];
		ucBuffer[4 + i * 6] = ptTemp->Addr[1];
		ucBuffer[5 + i * 6] = ptTemp->UpThr >> 8;
		ucBuffer[6 + i * 6] = ptTemp->UpThr;
		ucBuffer[7 + i * 6] = ptTemp->DownThr >> 8;
		ucBuffer[8 + i * 6] = ptTemp->DownThr;
		i++;
		if(i >= 9)
		{
			return -1;
		}
		ptTemp = ptTemp->ptNext;
	}
	uclen = i * 6 + 3;
	CrcData = MBCrcCheck(ucBuffer,uclen);
	ucBuffer[uclen] = CrcData >> 8;
	ucBuffer[uclen + 1] = CrcData;
	uclen += 2;
	if(ROM_ChangeData(MACHINE_ROM_ADDR, ucBuffer, uclen))
		return 0;
	else
		return -1;
}

static int MachineGetData(PT_ROMDataStruct ptROMData)
{
	uint8_t ucBuffer[100];
	uint8_t uclen,i = 0;
	PT_SenseDataStruct pTemp;
	uint8_t *pucTempAddr;
	
	ROM_GetData(MACHINE_ROM_ADDR, ucBuffer, 1);
	uclen = ucBuffer[0] * 6 + 5;
	if(uclen > 100)
	{
		return -1;
	}
	ROM_GetData(MACHINE_ROM_ADDR, ucBuffer, uclen);
	if(ReceCrcCheck(ucBuffer, uclen))
	{
		ptROMData->Num = ucBuffer[0];
		ptROMData->SendTime = ucBuffer[1] << 8 | ucBuffer[2];
		g_ptSenseMalloc = (PT_SenseDataStruct)pvPortMalloc(sizeof(T_SenseDataStruct) * ptROMData->Num);
		pTemp = g_ptSenseMalloc;
		ptROMData->SenseDataHead = pTemp;
		pucTempAddr = (uint8_t *)pvPortMalloc(2 * ptROMData->Num);
		for(i = 0; i < ptROMData->Num; i++)
		{
			pucTempAddr[0] = ucBuffer[3 + i * 6];
			pucTempAddr[1] = ucBuffer[4 + i * 6];
			pTemp->Addr = pucTempAddr;
			pTemp->UpThr = ucBuffer[5 + i * 6] << 8 | ucBuffer[6 + i * 6];
			pTemp->DownThr = ucBuffer[7 + i * 6] << 8 | ucBuffer[8 + i * 6];
			pTemp->ptNext = pTemp + 1;
			pTemp = pTemp->ptNext;
			pucTempAddr += 2;
		}
		(pTemp - 1)->ptNext = NULL;
		return 0;
	}
	return -1;
}
static void MachineFreeMalloc(void)
{
	vPortFree(g_ptSenseMalloc);
}

int MachineDataInit(void)
{
	return RegisterSaveOpr(&g_tMachineDataOpr);
}
